//
//  UIViewControllerExt.swift
//  FlameB
//
//  Created by 连俊 on 2020/7/30.
//  Copyright © 2020 连俊. All rights reserved.
//

import UIKit

extension UIViewController {
    public static func setKeyWindowRootViewController(root: UIViewController, currentViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController, animated: Bool) {
        var bottomVC: UIViewController? = getVisibleViewController(from: currentViewController)
        while bottomVC?.presentingViewController != nil {
            bottomVC = bottomVC?.presentingViewController
        }
        if let _ = bottomVC?.presentedViewController {
            bottomVC?.dismiss(animated: animated, completion: {
                UIApplication.shared.keyWindow?.rootViewController = root
            })
        } else {
            UIApplication.shared.keyWindow?.rootViewController = root
        }
    }

    public static func getVisibleViewController(from vc: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return UIViewController.getVisibleViewController(from: nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return UIViewController.getVisibleViewController(from: tc.selectedViewController)
        } else {
            if let pvc = vc?.presentedViewController {
                return UIViewController.getVisibleViewController(from: pvc)
            } else {
                return vc
            }
        }
    }

    public static func getTabbarViewController(from vc: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nc = vc as? UINavigationController {
            return UIViewController.getTabbarViewController(from: nc.visibleViewController)
        } else if let tc = vc as? UITabBarController {
            return tc
        } else {
            return nil
        }
    }
}
